import { onUnmounted } from 'vue'

type EventHandler<T extends Event = Event> = (event: T) => void

interface EventHandlers {
  [eventType: string]: EventHandler<any>
}

export default function useAddEventLister(eventHandlers: EventHandlers) {
  // 添加所有事件监听器
  Object.entries(eventHandlers).forEach(([eventType, handler]) => {
    window.addEventListener(eventType, handler)
  })

  // 返回清理函数
  const cleanup = () => {
    Object.entries(eventHandlers).forEach(([eventType, handler]) => {
      window.removeEventListener(eventType, handler)
    })
  }

  // 在组件卸载时自动清理
  onUnmounted(cleanup)

  return cleanup
}
